/*
* Copyright (c) 2016 . All Rights Reserved.
*/
package com.cgmnx.admin.biz.sys.impl;

import com.cgmnx.admin.biz.sys.FileUploadBiz;
import com.cgmnx.admin.common.bean.Template;
import com.cgmnx.admin.common.exception.Preconditions;
import com.cgmnx.admin.dao.entity.sys.UpdFileEntity;
import com.cgmnx.admin.service.sys.FileUploadService;
import com.cgmnx.admin.service.sys.UpdFileService;
import com.google.common.base.Optional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.io.InputStream;

/**
 * @author: created  Date: 16/12/20 Time: 下午3:32
 * @version: 1.0
 */
@Slf4j
@Service
public class FileUploadBizImpl implements FileUploadBiz {

    @Autowired
    @Qualifier("localFileUploadService")
    private FileUploadService fileUploadService;

    @Autowired
    private UpdFileService updFileService;

    @Override
    public Optional<UpdFileEntity> upload(final String originalFileName, final InputStream inputStream,
                                          final long size, final String userId, final String md5DigestAsHex) {

        return new Template<Optional<UpdFileEntity>>() {
            @Override
            protected void check() {
                Preconditions.checkArgument(StringUtils.isNotBlank(originalFileName), "上传的文件名不能为空");
                Preconditions.checkNotNull(inputStream, "上传的文件不能为空");
            }

            @Override
            protected Optional<UpdFileEntity> exec() throws Exception {

                String location = fileUploadService.upload(originalFileName, inputStream);

                if (StringUtils.isBlank(location)) {
                    return Optional.absent();
                }

                UpdFileEntity entity = new UpdFileEntity();
                entity.setUrl(location);
                entity.setFileName(originalFileName);
                entity.setEncryptFileName(md5DigestAsHex);
                entity.setSize(size);
                entity.setCreateUser(StringUtils.defaultString(userId));
                entity.setUpdateUser(StringUtils.defaultString(userId));
                entity.setContainer("");
                updFileService.save(entity);
                return Optional.fromNullable(entity);
            }
        }.execute();
    }

    @Override
    public Optional<InputStream> download(UpdFileEntity entity) {
        return new Template<Optional<InputStream>>() {
            @Override
            protected void check() {

            }

            @Override
            protected Optional<InputStream> exec() throws Exception {
                return null;
            }
        }.execute();
    }

}